package captcha

import (
	"api/dao/mysql"
	"api/model"
	"errors"
	"fmt"
	"image/color"
	"time"

	"github.com/mojocn/base64Captcha"
)

type MySQLStore struct {
}

// Set implement Set method
func (m MySQLStore) Set(id string, value string) (err error) {
	captcha := model.Captcha{
		ID:        id,
		Value:     value,
		CreatedAt: time.Now(),
	}
	_, err = mysql.AddCaptcha(&captcha)
	return
}

// Get implement Get method
func (m MySQLStore) Get(id string, clear bool) string {
	c, err := mysql.GetCaptcha(id)
	if err != nil {
		fmt.Printf("error: %v\n", err)
		return ""
	}

	if clear {
		//clear is true, verified, delete this captcha
		err = mysql.DeleteCaptcha(id)
		if err != nil {
			fmt.Printf("error: %v\n", err)
			return ""
		}
	}
	return c.Value
}

// Verify implement Verify method
func (m MySQLStore) Verify(id, answer string, clear bool) bool {
	v := m.Get(id, clear)
	return v == answer
}

// var store = base64Captcha.DefaultMemStore
var store base64Captcha.Store = MySQLStore{}

// GenerateCaptcha gennerate captcha
func GenerateCaptcha(length int) (id string, b64s string, err error) {
	var driver base64Captcha.Driver
	driverString := base64Captcha.DriverString{
		Height:          60,
		Width:           200,
		NoiseCount:      0,
		ShowLineOptions: 2 | 4,
		Length:          length,
		Source:          "1234567890qwertyuioplkjhgfdsazxcvbnm",
		BgColor:         &color.RGBA{R: 3, G: 102, B: 214, A: 125},
	}
	driver = driverString.ConvertFonts()
	c := base64Captcha.NewCaptcha(driver, store)
	return c.Generate()
}

// VerifyCaptcha verfiy captcha
func VerifyCaptcha(id string, verifyValue string) (err error) {
	result := store.Verify(id, verifyValue, true)
	if !result {
		return errors.New("captcha error")
	}

	return
}
